package com.example.bingobox.dialog;

import android.Manifest;
import android.app.Dialog;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.DialogFragment;

import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.example.bingobox.R;
import com.example.bingobox.model.State;

import java.util.ArrayList;
import java.util.List;

public class LocationSearchDialog extends DialogFragment implements PoiSearch.OnPoiSearchListener {
    private static final long LOCATION_TIMEOUT = 10000; // 10秒超时
    private EditText searchInput;
    private ListView resultList;
    private ArrayAdapter<String> adapter;
    private List<PoiItem> poiResults = new ArrayList<>();
    private OnLocationSelectedListener listener;
    private AMapLocationClient locationClient;
    private Handler timeoutHandler = new Handler();
    private AlertDialog loadingDialog;

    public static LocationSearchDialog newInstance() {
        return new LocationSearchDialog();
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
        LayoutInflater inflater = requireActivity().getLayoutInflater();
        View view = inflater.inflate(R.layout.dialog_location_search, null);

        try {
            locationClient = new AMapLocationClient(requireContext());
        } catch (Exception e) {
            e.printStackTrace();
        }

        initializeViews(view);
        setupListeners(view);

        return builder.setView(view)
                .setTitle("搜索位置")
                .setNegativeButton("取消", null)
                .create();
    }

    private void initializeViews(View view) {
        searchInput = view.findViewById(R.id.search_input);
        resultList = view.findViewById(R.id.result_list);
        adapter = new ArrayAdapter<>(requireContext(), android.R.layout.simple_list_item_1);
        resultList.setAdapter(adapter);

        resultList.setOnItemClickListener((parent, v, position, id) -> {
            if (position < poiResults.size()) {
                PoiItem poi = poiResults.get(position);
                State.Location location = new State.Location(
                    poi.getTitle(),
                    poi.getLatLonPoint().getLatitude(),
                    poi.getLatLonPoint().getLongitude()
                );
                location.setAddress(poi.getSnippet());
                
                if (listener != null) {
                    listener.onLocationSelected(location);
                }
                dismiss();
            }
        });
    }

    private void setupListeners(View view) {
        view.findViewById(R.id.btn_search_location).setOnClickListener(v -> {
            String query = searchInput.getText().toString().trim();
            if (!query.isEmpty()) {
                searchLocation(query);
            }
        });
    }

    private void getCurrentLocation() {
        if (ActivityCompat.checkSelfPermission(requireContext(), 
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(requireContext(), "需要位置权限", Toast.LENGTH_SHORT).show();
            return;
        }

        showLoading("正在获取位置信息...");

        AMapLocationClientOption option = new AMapLocationClientOption();
        option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        option.setOnceLocation(true);
        option.setNeedAddress(true);
        locationClient.setLocationOption(option);

        timeoutHandler.postDelayed(() -> {
            hideLoading();
            Toast.makeText(requireContext(), "定位超时，请重试", Toast.LENGTH_SHORT).show();
            locationClient.stopLocation();
        }, LOCATION_TIMEOUT);

        locationClient.setLocationListener(aMapLocation -> {
            timeoutHandler.removeCallbacksAndMessages(null);
            if (aMapLocation != null) {
                if (aMapLocation.getErrorCode() == 0) {
                    String locationName;
                    if (aMapLocation.getPoiName() != null && !aMapLocation.getPoiName().isEmpty()) {
                        locationName = aMapLocation.getPoiName();
                    } else if (aMapLocation.getAoiName() != null && !aMapLocation.getAoiName().isEmpty()) {
                        locationName = aMapLocation.getAoiName();
                    } else {
                        locationName = aMapLocation.getStreet() != null ? aMapLocation.getStreet() : "未知位置";
                    }

                    StringBuilder addressBuilder = new StringBuilder();
                    if (aMapLocation.getProvince() != null) {
                        addressBuilder.append(aMapLocation.getProvince());
                    }
                    if (aMapLocation.getCity() != null) {
                        addressBuilder.append(aMapLocation.getCity());
                    }
                    if (aMapLocation.getDistrict() != null) {
                        addressBuilder.append(aMapLocation.getDistrict());
                    }
                    if (aMapLocation.getStreet() != null) {
                        addressBuilder.append(aMapLocation.getStreet());
                    }

                    State.Location location = new State.Location(
                        locationName,
                        aMapLocation.getLatitude(),
                        aMapLocation.getLongitude()
                    );
                    location.setAddress(addressBuilder.toString());

                    if (listener != null) {
                        listener.onLocationSelected(location);
                    }
                    dismiss();
                } else {
                    Toast.makeText(requireContext(), 
                        "定位失败: " + aMapLocation.getErrorInfo(), 
                        Toast.LENGTH_SHORT).show();
                }
            }
            hideLoading();
        });

        locationClient.startLocation();
    }

    private void searchLocation(String keyword) {
        showLoading("正在搜索...");
        try {
            PoiSearch.Query query = new PoiSearch.Query(keyword, "", "");
            query.setPageSize(10);
            query.setPageNum(1);
            
            PoiSearch poiSearch = new PoiSearch(requireContext(), query);
            poiSearch.setOnPoiSearchListener(this);
            poiSearch.searchPOIAsyn();
        } catch (AMapException e) {
            hideLoading();
            Toast.makeText(requireContext(), "搜索失败: " + e.getErrorMessage(), 
                Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onPoiSearched(PoiResult result, int rCode) {
        hideLoading();
        if (rCode == AMapException.CODE_AMAP_SUCCESS) {
            if (result != null && result.getPois() != null) {
                poiResults.clear();
                adapter.clear();
                
                for (PoiItem poi : result.getPois()) {
                    poiResults.add(poi);
                    String displayName = poi.getTitle();
                    if (poi.getSnippet() != null && !poi.getSnippet().isEmpty()) {
                        displayName += "\n" + poi.getSnippet();
                    }
                    adapter.add(displayName);
                }

                if (poiResults.isEmpty()) {
                    Toast.makeText(requireContext(), "未找到相关位置", Toast.LENGTH_SHORT).show();
                }
            }
        } else {
            Toast.makeText(requireContext(), "搜索失败，错误码: " + rCode, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {}

    private void showLoading(String message) {
        if (loadingDialog == null) {
            loadingDialog = new AlertDialog.Builder(requireContext())
                .setMessage(message)
                .setCancelable(false)
                .create();
        }
        loadingDialog.setMessage(message);
        loadingDialog.show();
    }

    private void hideLoading() {
        if (loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
    }

    public interface OnLocationSelectedListener {
        void onLocationSelected(State.Location location);
    }

    public void setOnLocationSelectedListener(OnLocationSelectedListener listener) {
        this.listener = listener;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (locationClient != null) {
            locationClient.onDestroy();
        }
    }
} 